package myself.study.network.udp.examples.chatroom;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ReceiveRunnable implements Runnable {
	
	private DatagramSocket serverSocket ;

	public ReceiveRunnable(DatagramSocket serverSocket) {
		this.serverSocket = serverSocket ;
	}

	@Override
	public void run() {
		try {
			while(true) {
				//创建接收数据包
				byte[] buf = new byte[1024] ;
				DatagramPacket packet = new DatagramPacket(buf, buf.length) ;
				//接收客户端发送过来的数据包
				serverSocket.receive(packet) ;
				//解析数据包
				String s = new String(packet.getData(), 0, packet.getData().length);
				//处理数据
				System.out.println("from [" + packet.getAddress().getHostAddress() + "] data is : " + s);
			}
		} catch (IOException e) {
			e.printStackTrace() ;
		}
	}
}
